<template>
  <div class="taggingMode-bg">
    <div class="taggingMode-view">
      <div class="title">
        <span class="title-tip">{{
          $t("message.cadViewer.taggingMode.title")
        }}</span>
        <i class="el-icon-close" @click="onCancelClick"></i>
      </div>
      <div class="taggingMode-body">
        <div class="markup-file-view">
          <span class="markup-file-message">{{
            $t("message.cadViewer.taggingMode.select_file")
          }}</span>
          <el-button class="markup-btn-cancel" @click="onOkClick">OK</el-button>
        </div>
        <div class="markup-file-view">
          <el-select v-model="selectId" placeholder class="select-input" @change="selectIdFun()">
            <!-- :label="item.markUpFileName" -->
            <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <el-button class="markup-btn-cancel" @click="onCancelClick">
            Cancel
          </el-button>
        </div>
        <div class="markup-file-view">
          <div class="icon-view">
            <el-upload class="upload-demo" :action="action" multiple :on-error="uploadFalse" :on-success="uploadSuccess"
              :before-upload="beforeAvatarUpload" :show-file-list="false" :http-request="CheckMarkupFileFun"
              ref="upload" :data="form" :headers="token">
              <div class="icon-item">
                <i class="el-icon-upload2 el-icon"></i>
                <span size="small" type="text">{{
                  $t("message.public.uploaded")
                }}</span>
              </div>
            </el-upload>
            <div class="icon-item" @click="downData">
              <i class="el-icon-download el-icon"></i>
              <span>{{ $t("message.homePageTable.download") }}</span>
            </div>
            <div class="icon-item" @click="deleteData">
              <i class="el-icon-delete el-icon"></i>
              <span>{{ $t("message.public.delete") }}</span>
            </div>
          </div>
          <el-button type="primary" class="markup-btn-cancel" @click="onCreateNewFile">
            {{ $t("message.cadViewer.taggingMode.addfile") }}
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getMarkUpFile,
  delMarkUpFile,
  CheckMarkupFile,
  addMarkUpFile,
} from "../../api/api";
import { getLocalStorage } from "../../utils/storage";
import BASE from "../../utils/base";
// 导出模块
export default {
  // 模块名字
  name: "taggingMode",
  props: {
    inFileID: {
      type: String,
      default: "",
    },
  },
  // 模块数据
  data() {
    //数据
    return {
      options: [],
      value: "",
      action: BASE.IP + "/api/File/addMarkUpFile",
      form: {
        creator: getLocalStorage("userID"),
        modifier: getLocalStorage("userID"),
        FileID: this.inFileID,
        cover: null,
      },
      selectId: "",
      formData: "",
      token: { 'Authorization': "Bearer " + ((sessionStorage.token && getLocalStorage('token')) ? sessionStorage.token : "") },
    };
  },
  // 注册组件
  components: {},
  // 监听指定值，只有指定值变化，才会触发
  watch: {},
  // 里面的函数只有调用才会执行（实时计算）里面是定义的方法
  methods: {
    //文件上传失败触发
    uploadFalse(response, file, fileList) {

    },
    //文件上传成功触发
    uploadSuccess(response, file, fileList) {

    },
    beforeAvatarUpload(file) {
      let formData = new FormData();
      formData.append("file", file);
      formData.append("creator", this.form.creator);
      formData.append("modifier", this.form.modifier);
      // formData.append("FileID", this.form.FileID);
      formData.append("FileID", this.inFileID);
      let dataJson = {
        // fileID: '',
        // fileID: this.form.FileID,
        fileID: this.inFileID,
        markupFileName: file.name,
      };
      CheckMarkupFile(dataJson).then((res) => {
        if (res.data.code != 0) {
          this.$confirm(
            res.data.msg,
            this.$t("message.public.tip"),
            {
              confirmButtonText: this.$t("message.public.confirm"),
              cancelButtonText: this.$t("message.public.markupcancel"),
              type: "warning",
            }
          )
            .then(() => {
              if (formData.get("corer")) {
                formData.set("corer", 1);
              } else {
                formData.append("cover", 1);
              }
              this.addMarkUpFileApi(formData);
            })
            .catch(() => {
              // if (formData.get("corer")) {
              //   formData.set("corer", 2);
              // } else {
              //   formData.append("cover", 2);
              // }
              // this.addMarkUpFileApi(formData);
            });
          return;
        }
        if (formData.get("corer")) {
          formData.set("corer", 0);
        } else {
          formData.append("cover", 0);
        }
        this.addMarkUpFileApi(formData);
      });
    },
    addMarkUpFileApi(formData) {
      addMarkUpFile(formData).then((res) => {
        if (res.data.code != 0) {
          this.getDataList();
          this.$alert(res.data.msg, '', {
            confirmButtonText: 'OK',
            type: 'warning',
          });
          return;
        }
        this.$message({
          message: this.$t("message.homePageTable.suploaded"),
          type: "success",
        });
        this.getDataList();
      });
    },
    CheckMarkupFileFun(params) {
      console.log(params);
    },
    downData(row) {
      // let name = row.name + "." + row.ext;
      // let url = row.sourcePath;
      if (this.selectId == "") {
        return;
      }
      this.options.forEach((element) => {
        if (this.selectId == element.id) {
          console.log(element, `${element.name}.${element.ext}`, '12121');

          // this.fdownload(element.path, element.markUpFileName + ".xml");
          this.$downFileByBlob({ path: element.path, isDown: true, fileName: `${element.name}.${element.ext}`, isOpenNewBlank: false })
          console.log(element.path);
        }
      });
    },
    fdownload(url, filename) {
      let _this = this;
      this.getBlob(url, function (blob) {
        _this.saveAs(blob, filename);
      });
    },
    getBlob(url, cb) {
      var xhr = new XMLHttpRequest();
      xhr.open("GET", url, true);
      xhr.responseType = "blob";
      xhr.onload = function () {
        if (xhr.status === 200) {
          cb(xhr.response);
        }
      };
      xhr.send();
    },
    saveAs(blob, filename) {
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, filename);
      } else {
        var link = document.createElement("a");
        var body = document.querySelector("body");
        link.href = window.URL.createObjectURL(blob);
        link.download = filename;
        // fix Firefox
        link.style.display = "none";
        body.appendChild(link);
        link.click();
        body.removeChild(link);
        window.URL.revokeObjectURL(link.href);
      }
    },
    selectIdFun() {
      this.options.forEach((element) => {
        console.log(this.selectId == element.id);
        if (this.selectId == element.id) {
          this.form.FileID = element.fileID;
          console.log(this.form.FileID, 'fsdfdsfdsf');
        }
      });
    },
    deleteData() {
      console.log("--");
      if (this.selectId == "") {
        return;
      }

      this.$confirm(
        this.$t("message.cadViewer.taggingMode.deleteFlie"),
        this.$t("message.public.tip"),
        {
          confirmButtonText: this.$t("message.public.confirm"),
          cancelButtonText: this.$t("message.public.cancel"),
          type: "warning",
        }
      )
        .then(() => {
          let JsonData = {
            id: [this.selectId],
          };
          delMarkUpFile(JsonData).then((res) => {
            if (res.data.code != 0) {
              return;
            }
            this.selectId = "";
            this.getDataList();
          });
        })
        .catch(() => { });
    },
    getDataList() {
      console.log('inFileID', this.inFileID);
      let dataJson = {
        fileID: this.inFileID,
        markUpName: "",
        pageIndex: 1,
        pageSize: 1000,
        pltCode: Number(this.$route.query.pltCode),
        isShow: false
      };
      getMarkUpFile(dataJson).then((res) => {
        this.options = [];
        if (res.data.code != 0) {
          return;
        }
        this.options = res.data.data;
        this.selectId = this.options[0].id;
      });
    },

    onOkClick() {
      var _self = this;
      var re = null;
      for (var i = 0; i < _self.options.length; i++) {
        if (_self.options[i].id == _self.selectId) re = _self.options[i];
      }

      if (re == null) {
        console.log("e == null");
        this.$message({
          message: this.$t("message.cadViewer.noSelectedXml"),
          type: "warning",
        });
        return;
      }

      this.$emit("onOkClick", re);
    },

    onCancelClick() {
      this.$emit("onCancelClick", null);
    },

    onCreateNewFile() {
      this.$emit("onNewFileClick", null);
    },
  },
  // 创建前状态(里面是操作)
  beforeCreate() { },
  // 创建完毕状态(里面是操作)
  created() {
    this.getDataList();
  },
  // 挂载前状态(里面是操作)
  beforeMount() { },
  // 挂载结束状态(里面是操作)
  mounted() { },
  // 更新前状态(里面是操作)
  beforeUpdate() { },
  // 更新完成状态(里面是操作)
  updated() { },
  // 销毁前状态(里面是操作)
  beforeDestroy() { },
  // 销毁完成状态(里面是操作)
  destroyed() { },
};
</script>
<style lang="scss" scoped>
.taggingMode-bg {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.1);
}

.taggingMode-view {
  width: 488px;
  height: 208px;
  background: rgba(255, 255, 255, 1);
  box-shadow: 0px 12px 48px 16px rgba(0, 0, 0, 0.03),
    0px 9px 28px 0px rgba(0, 0, 0, 0.05), 0px 6px 16px -8px rgba(0, 0, 0, 0.08);
  position: absolute;
  top: 40%;
  left: 50%;
  transform: translate(-50%, -50%);

  .title {
    width: 100%;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: #fafafa;

    .title-tip {
      margin-left: 24px;
      font-weight: 600;
      color: rgba(0, 0, 0, 0.85);
      font-size: 16px;
    }

    .el-icon-close {
      margin-right: 24px;
      color: #000000;
      font-size: 16px;
      cursor: pointer;
    }
  }

  .taggingMode-body {
    width: 100%;
    height: calc(100% - 40px);
    padding: 16px 24px 24px 24px;

    .markup-file-view {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 16px;

      .markup-file-message {
        font-size: 14px;
        color: rgba(0, 0, 0, 0.85);
      }

      .markup-btn-cancel {
        min-width: 88px !important;
        height: 32px;
        // background: rgba(255, 255, 255, 1);
        // border: 1px solid rgba(217, 217, 217, 1);
        // border-radius: 4px;
        // outline: none;
        padding: 0 8px;
      }

      .select-input {
        width: 294px;
        height: 32px;

        ::v-deep .el-input--suffix .el-input__inner {
          height: 32px;
        }

        ::v-deep .el-input__icon {
          line-height: 32px;
        }
      }

      .icon-view {
        display: flex;
        align-items: center;
        justify-content: flex-start;
        height: 32px;

        .icon-item {
          margin-right: 16px;

          .el-icon {
            font-size: 16px;
            cursor: pointer;
            color: rgba(0, 0, 0, 0.65);
          }

          span {
            font-size: 16px;
            cursor: pointer;
            color: rgba(0, 0, 0, 0.65);
            margin-left: 8px;
          }
        }
      }
    }
  }
}
</style>
